<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Loader;
use think\Session;
use think\Db;
use think\exception\HttpException;
use think\Config;

class Calendar extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->except(['id']);

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 写入数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                //使用模型写入，可以在模型中定义更高级的操作
                $model = new $modelClass();
                $ret = $model->isUpdate(false)->save($data);

            } else {
                // 简单的直接使用db写入
                Db::startTrans();
                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->insert($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv('添加成功');
        } else {
            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }




    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 更新数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                // 使用模型更新，可以在模型中定义更高级的操作
                $model = new $modelClass();
                $ret = $model->isUpdate(true)->save($data, ['id' => $data['id']]);



                $times = $data['times'];

                $newtimes =json_decode(htmlspecialchars_decode($times),true) ;


                if($ret == 1) {

                    $wechatAuth = new \WechatAuth(Config::get('weixin.appId'), Config::get('weixin.appSecret'));

                    $wechatAuth->getAccessToken();

                    $ordergroups = Db::name("queue_order")->where(['status' => "1"])->order("queue_time asc")->field('uid,queue_time,bisname,id')->select();

                    foreach ($ordergroups as $gro) {

                        if (in_array(date('Y-m-d', $gro['queue_time']), $newtimes)) {

                            Db::name("queue_order")->where('id', $gro['id'])->update(array('status' => '2'));

                            $openid = model('Member')->where(['uid' => $gro['uid']])->value('openid');

                            $data1 = array(
                                'first' => array('value' => "对不起,您的预约已取消", 'color' => "#00CD00"),
                                'keyword1' => array('value' => $gro['bisname'], 'color' => '#EE5C42'),
                                'keyword2' => array('value' => date('Y-m-d', $gro['queue_time']), 'color' => '#030303'),
                                'keyword3' => array('value' => '由于系统原因您预约的时间不能提供服务', 'color' => '#030303'),
                                'remark' => array('value' => '欢迎再次使用我们的服务', 'color' => '#030303'),
                            );
                            $result = $wechatAuth->doSendTpl($openid, 'NAXS7QUctxshBx0kVy6fAV5gC6Ykk7chsIVDG3zl-MU', 'http://bhgt.jslcwy.com/#/orderDone', $data1);
                        }
                    }


                }



                } else {
                // 简单的直接使用db更新
                Db::startTrans();
                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->where('id', $data['id'])->update($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv("编辑成功");
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel($controller)->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }


            $json = json_decode(htmlspecialchars_decode($vo['times']) ,true);

            foreach($json as $obj){

                $zero1=date("y-m-d");
                $zero2= $obj;
                if(strtotime($zero1)> strtotime($zero2)){

                    $key=array_search($obj ,$json);

                    array_splice($json,$key,1);

                }
            }

            $vo['times'] = htmlentities(json_encode($json));


            $this->view->assign("vo", $vo);

            return $this->view->fetch();
        }
    }

}
